package wat.serwerapp.admins;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
import wat.ziszcommon.invoker.Method;
import wat.serwerapp.usermgmt.ldap.RoleManager;

/**
 *
 * @author P.B. & L.G. & K.K.
 */
public class SetRolesList implements Method {

   private static Set<String> owners;

   public Set<String> getOwners() {
      if (owners == null) {
         owners = new HashSet<String>();
         owners.add("pl.edu.wat.erp.client.administration.UserAdministrationClient");
      }
      return owners;
   }

   public String invoke(String parameters) {
      String rolesList = parameters;

      HashMap<String, Map<String, String>> roles = new HashMap<String, Map<String, String>>();

      for (String rolesAndRights : rolesList.split(";")) {
         String[] role = rolesAndRights.split(":");
         String roleName = role[0];
         HashMap<String, String> rightsMap = new HashMap<String, String>();
         if (role.length == 2) { //posiada uprawnienia
            String[] rights = role[1].split(",");
            for (String right : rights) {
               String[] s = right.split("-");
               rightsMap.put(s[0], s[1]);
            }
         }
         roles.put(RoleManager.roleToLdapFormat(roleName), rightsMap);
      }

      Set<String> rolesKeys = roles.keySet();
      try {
         for (String role : rolesKeys) {
            RoleManager.setRights(role, roles.get(role));
         }
         return "OK";
      } catch (NamingException ex) {
         Logger.getLogger(SetRolesList.class.getName()).log(Level.SEVERE, null, ex);
         return "NamingException";
      } catch (Exception ex) {
         Logger.getLogger(SetRolesList.class.getName()).log(Level.SEVERE, null, ex);
         return "Exception";
      }

   }

   public List invoke(List parameters) {
      throw new UnsupportedOperationException("Not supported yet.");
   }
}
